package com.zhangzhan.gulimallseckill.scheduled;

import com.zhangzhan.gulimallseckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/7/4 18:34
 */
@EnableScheduling
@EnableAsync
@Component
@Slf4j
public class SeckillScheduled {


    @Autowired
    private RedissonClient redissonClient;


    @Autowired
    private SeckillService seckillService;

    private final String SECKILL_LOCK = "seckill:lock";

    /**
     * 定时存入三天后的秒杀活动
     */
    @Async
    @Scheduled(cron = "* * 2 * * ? ")
    public void shelves3DayAfterSeckill() {
        RLock lock = redissonClient.getLock(SECKILL_LOCK);
        lock.lock(10, TimeUnit.SECONDS);
        System.out.println(Thread.currentThread().getId()+"加锁");
        try {
            seckillService.shelves3DayAfterSeckill();
        } finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getId()+"解锁");
        }
    }


}
